/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
import type { ConnectState } from '@/models/connect';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import React, { useRef, useState } from 'react';
import type { CurrentUser, Dispatch } from 'umi';
import { connect } from 'umi';
import type { GetCabinetParamsType, CabinetExportParams } from '@/services/device';
import { getPowerLine, powerLineDataToCsvApi } from '@/services/device';
import { Tag, Button, message, Spin, Popconfirm } from 'antd';
import Manage from './components/manage'
import SellerSelectModal from '@/components/SellerSelectModal/SellerSelectModal';

interface PowerlineProps {
  dispatch: Dispatch;
  userState?: CurrentUser;
}

// "name": "绿地",
// "addr": "广东省广州市绿地中央广场",
// "powerline_id": "20B1P000001",//充电线编号
// "status": 1,//充电线状态(1为正常,0为损坏,2为测试,3为异常)
// "heartbeat_time": "2020-07-22 22:40:40",//最后使用时间
// "type": "2",//1-充电宝机柜 ，2-充电线
// "device_type": 1,//1-密码充电线 ，2-蓝牙充电线
// "sid": 637,//商户编号
interface PowerlineItemInfo {
  addr: string;
  powerline_id: string;
  device_type: string;
  status: string; // 充电线状态
  name: string;
  sid: string; // 商户编号
  type: string; // 设备类型
  binding: boolean; // 是否铺货
}

const PowerlineList: React.FC<PowerlineProps> = (props) => {
  const { userState } = props;
  const [page, setPage] = useState(1); // 设置页数
  const [limit, setLimit] = useState(20); // 设置数据读取数
  const [total, setTotal] = useState(0); // 设置数据总数
  const [deviceId, setDeviceId] = useState(''); // 设置过滤机柜编号
  const [sid, setSid] = useState(''); // 过滤商户id
  const [name, setName] = useState(''); // 设置过滤商户名称
  const [binding, setBinding] = useState(0); // 查看是否铺货
  const [aid, setAid] = useState(''); // 查看代理id
  const [aname, setAname] = useState(''); // 设置代理名称
  const [loading, setLoading] = useState(false); // 是否加载中
  const ref = useRef<ActionType>();
       
  // 表格配置
  let columns: ProColumns<PowerlineItemInfo>[] = [
    // {
    //   title: '操作',
    //   key: 'option',
    //   valueType: 'option',
    //   fixed: 'left',
    //   render: (_, row) => {
    //     return row.binding === true ? (
    //       <Popconfirm
    //         title="确定要解绑吗?"
    //         onConfirm={() => unbindSellerDevice(row.powerline_id)}
    //         okText="确定"
    //         cancelText="取消"
    //       >
    //         <a>解绑(商户)</a>
    //       </Popconfirm>
    //     ) : (
    //       <SellerSelectModal
    //         deviceId={row.powerline_id}
    //         userState={userState}
    //         confirmFn={bindSellerDevice}
    //       ></SellerSelectModal>
    //     );
    //   },
    // },
    {
      title: '充电线编号',
      dataIndex: 'powerline_id',
      valueType: 'textarea',
      copyable: true,
    },
    {
      title: '商户Id',
      dataIndex: 'sid',
      copyable: true,
    },
    {
      title: '商户名称',
      dataIndex: 'sname',
      copyable: true,
    },
    {
      title: '代理Id',
      dataIndex: 'aid',
      hideInTable: true,
    },
    {
      title: '代理名称',
      dataIndex: 'aname',
      hideInTable: true,
    },
    {
      title: '详细地址',
      dataIndex: 'addr',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: false,
      render: (_, row) => {
        if (row.status == '1') {
          return <Tag color="green">正常</Tag>;
        }
        if (row.status == '0') {
          return <Tag color="red">损坏</Tag>;
        }
        if (row.status == '2') {
          return <Tag color="orange">测试</Tag>;
        }
        return <Tag color="magenta">异常</Tag>;
      },
    },
    {
      title: '设备型号',
      dataIndex: 'device_type',
      search: false,
      valueEnum: {
        1: { text: '密码充电线', status: 'Processing' },
        2: { text: '蓝牙充电线', status: 'Processing' },
      },
    },
    {
      title: '是否铺货',
      dataIndex: 'binding',
      valueEnum: {
        1: { text: '全部' },
        true: { text: '已铺货', status: 'Processing' },
        false: { text: '未铺货', status: 'Error' },
      },
    },
    {
      title: '计费说明',
      dataIndex: 'charge_rule',
      search: false,
    },
  ];
  // 判断代理等级是不是大于店铺代理
  if (
    props.userState &&
    props.userState.type &&
    (props.userState.type === 5 || props.userState.type < 5)
  ) {
    columns = columns.concat([
      {
        title: '店铺管理ID',
        search: false,
        dataIndex: 'said',
        copyable: true,
      },
      {
        title: '店铺管理名称',
        search: false,
        dataIndex: 'saname',
      },
      {
        title: '店铺管理分润',
        search: false,
        dataIndex: 'sbrokerage',
        valueType: 'percent',
      },
    ]);
  }
  // 判断代理等级是不是大于等于业务代理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 1
  ) {
    columns = columns.concat([
      {
        title: '业务代理ID',
        search: false,
        dataIndex: 'baid',
        copyable: true,
      },
      {
        title: '业务代理名称',
        search: false,
        dataIndex: 'baname',
      },
      {
        title: '业务代理分润',
        search: false,
        dataIndex: 'bbrokerage',
        valueType: 'percent',
      },
    ]);
  }
  // 判断代理等级是不是大于等于区域经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 2
  ) {
    columns = columns.concat([
      {
        title: '区域经理ID',
        search: false,
        dataIndex: 'aaid',
        copyable: true,
      },
      {
        title: '区域经理名称',
        search: false,
        dataIndex: 'aaname',
      },
      {
        title: '区域经理收益',
        search: false,
        dataIndex: 'abrokerage',
        valueType: 'percent',
      },
    ]);
  }
  // 判断代理等级是不是大于等于市级经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type >= 3
  ) {
    columns = columns.concat([
      {
        title: '市级代理ID',
        search: false,
        dataIndex: 'caid',
        copyable: true,
      },
      {
        title: '市级代理名称',
        search: false,
        dataIndex: 'caname',
      },
      {
        title: '市级代理收益',
        search: false,
        dataIndex: 'cbrokerage',
        valueType: 'percent',
      },
    ]);
  }
  // 判断代理等级是不是大于等于省级经理
  if (
    props.userState &&
    props.userState.type &&
    props.userState.type !== 5 &&
    props.userState.type === 4
  ) {
    columns = columns.concat([
      {
        title: '省级代理ID',
        search: false,
        dataIndex: 'paid',
        copyable: true,
      },
      {
        title: '省级代理名称',
        search: false,
        dataIndex: 'paname',
      },
      {
        title: '省级代理分润',
        search: false,
        dataIndex: 'pbrokerage',
      },
    ]);
  }

  return (
    <PageContainer>
      <Spin spinning={loading} tip="导出中...">
        <ProTable
          headerTitle="充电线管理"
          onReset={() => {
            setPage(1);
          }}
          // eslint-disable-next-line @typescript-eslint/no-shadow
          rowKey={(columns) => columns.powerline_id}
          scroll={{ x: 'max-content' }}
          search={{
            defaultCollapsed: false,
          }}

          request={async () => {
            const data: GetCabinetParamsType = {
              uId: userState?.id!,
              userType: userState?.user_type!,
              token: userState?.token!,
              page,
              limit,
              device_id: deviceId,
              binding,
              sid,
              sname: name,
              aid,
              aname,
            };
            return getPowerLine(data);
          }}
          postData={(res) => {
            setTotal((res as any).num);
            return (res as any).data;
          }}
          beforeSearchSubmit={(params: any) => {
            // 查找机柜
            if (params.powerline_id) {
              setDeviceId(params.powerline_id);
            } else {
              setDeviceId('');
            }
            // 设置代理id
            if (params.sid) {
              setSid(params.sid);
            } else {
              setSid('');
            }
            // 查找商户
            if (params.name) {
              setName(params.name);
            } else {
              setName('');
            }
            // 查看是否铺货
            if (params.binding === 'true') {
              setBinding(1);
            } else if (params.binding === 'false') {
              setBinding(2);
            } else {
              setBinding(0);
            }
            // 设置代理id
            if (params.aid) {
              setAid(params.aid);
            } else {
              setAid('');
            }
            // 设置代理名称
            if (params.aname) {
              setAname(params.aname);
            } else {
              setAname('');
            }
            return params;
          }}
          // 工具栏
          toolBarRender={() => [
            <Manage
              title="批量操作(商户)"
              type={1}
              key="manage"
              updateData={() => ref.current?.reload()}
            ></Manage>,
            <Manage
              title="批量操作(代理)"
              type={2}
              key="manage"
              updateData={() => ref.current?.reload()}
            ></Manage>,
            <Button
              onClick={async () => {
                try {
                  const data: CabinetExportParams = {
                    uId: Number(userState?.id!),
                    userType: Number(userState?.user_type!),
                    token: userState?.token!,
                    device_id: deviceId,
                    sid: sid ? Number(sid) : null,
                    sname: name,
                    aid: aid ? Number(aid) : null,
                    aname,
                    binding,
                  };
                  setLoading(true);
                  const res = await powerLineDataToCsvApi(data);
                  if (res.code === 0) {
                    const newUrl = await (await fetch(res.data)).arrayBuffer(); // 将返回数据转成buff对象
                    const nowTime = new Date().toLocaleString();
                    const fileName = `${nowTime}充电线列表.csv`;
                    const myBlob = new Blob([newUrl], { type: 'text/csv,charset=UTF-8' });
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(myBlob);
                    link.download = fileName;
                    link.click();
                    link.remove();
                    URL.revokeObjectURL(link.href);
                    message.success('导出成功');
                    setLoading(false);
                  } else {
                    message.error(res.msg);
                  }
                } catch (error) {
                  console.log(error);
                }
              }}
            >
              导出
            </Button>,
          ]}
          pagination={{
            pageSize: limit,
            total,
            onChange: (page) => {
              setPage(page);
            },
            onShowSizeChange: (_, size) => {
              setLimit(size);
            },
          }}
          columns={columns}
        ></ProTable>
      </Spin>
    </PageContainer>
  );
};

export default connect(({ user }: ConnectState) => ({ userState: user.currentUser }))(
  PowerlineList,
);
